package com.epfresh.supplier.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.InputFilter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.epfresh.api.entity.RequestEntityMapSupply;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.global.DataManager;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.LocalDisplay;
import com.epfresh.api.views.MaxLengthWatcher;
import com.epfresh.supplier.R;
import com.epfresh.supplier.constant.Constant;
import com.epfresh.supplier.entity.ProductAddEntity;
import com.epfresh.supplier.view.tag.FlowLayout;
import com.epfresh.supplier.view.tag.TagAdapter;
import com.epfresh.supplier.view.tag.TagFlowLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ProductAddOtherActivity extends BaseActivity {


    private EditText ed;
    private TextView tvAdd;

    private TagFlowLayout tagFlowLayout;


    private List<String> list = new ArrayList<>();

    private TagAdapter<String> tagAdapter;

    int tagW = -1;


    String area;
    String brand;
    String level;
    String type;
    String content;
    String species;
    private String productId;
    private String varietyName;
    private String nameId;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_add_category_varieties);
        if (savedInstanceState != null) {
            getIntent().putExtra("productId", savedInstanceState.getString("productId"));
            getIntent().putExtra("area", savedInstanceState.getString("area"));
            getIntent().putExtra("level", savedInstanceState.getString("level"));
            getIntent().putExtra("brand", savedInstanceState.getString("brand"));
            getIntent().putExtra("page_type", savedInstanceState.getString("page_type"));
            getIntent().putExtra("varietyName", savedInstanceState.getString("varietyName"));
            getIntent().putExtra("nameId", savedInstanceState.getString("nameId"));
            getIntent().putExtra("content", savedInstanceState.getString("content"));
            getIntent().putExtra("species", savedInstanceState.getString("species"));
            getIntent().putExtra("tagPackage", savedInstanceState.getString("tagPackage"));
            getIntent().putExtra("dataProduct", savedInstanceState.getString("dataProduct"));
            String dataProduct = getIntent().getStringExtra("dataProduct");
            if(dataProduct != null && !"".equals(dataProduct)) {
                DataManager.getInstance().setProductAddEntity(new Gson().fromJson(dataProduct,ProductAddEntity.class));
            }
        }
        rightbtn.setText("确定");
        rightbtn.setVisibility(View.VISIBLE);
        rightbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String s = ed.getText().toString();
                if ("5".equals(type)) {
                    if (s != null && !"".equals(s)) {
                        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.hideSoftInputFromWindow(ed.getWindowToken(), 0); //强制隐藏键盘
                        Intent intent = new Intent();
                        intent.putExtra("result", s);
                        setResult(RESULT_OK, intent);
                        finish();
                    } else {
                        toast("请添加品名");
                    }
                } else if ("3".equals(type)) {
//                    if (s != null && !"".equals(s.trim())){
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(ed.getWindowToken(), 0); //强制隐藏键盘
                    Intent intent = new Intent();
                    intent.putExtra("result", s);
                    setResult(RESULT_OK, intent);
                    finish();
//                    }else {
//                        toast("请添加产地");
//                    }
                }
            }
        });
        area = getIntent().getStringExtra("area");
        brand = getIntent().getStringExtra("brand");
        level = getIntent().getStringExtra("level");
        type = getIntent().getStringExtra("page_type");
        productId = getIntent().getStringExtra("productId");
        nameId = getIntent().getStringExtra("nameId");
        varietyName = getIntent().getStringExtra("varietyName");
        content = getIntent().getStringExtra("content");
        species = getIntent().getStringExtra("species");
        initAddView();
//        level(等级)，brand(品牌)，origin(产地)
        if ("4".equals(type)) {//等级
            request(nameId,varietyName,"level");
            ed.setHint("请添加等级");
            toolbarTitle.setText("等级");
            ed.addTextChangedListener(new MaxLengthWatcher(5, ed));
        } else if ("2".equals(type)) {//品牌
            request(nameId,varietyName,"brand");
            ed.setHint("请添加品牌");
            toolbarTitle.setText("品牌");
            ed.addTextChangedListener(new MaxLengthWatcher(10, ed));
        } else if ("3".equals(type)) {//产地
            request(nameId,varietyName,"origin");
            ed.setHint("请添加产地");
            toolbarTitle.setText("产地");
            ed.addTextChangedListener(new MaxLengthWatcher(10, ed));
        } else if ("5".equals(type)) {//品名
            request(nameId,varietyName,"species");
            ed.setHint("请添加品名");

            String s = "品名 <font color=\"#ff0000\">*</font>";
            toolbarTitle.setText(Html.fromHtml(s));
            ed.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10)});
            ed.addTextChangedListener(new MaxLengthWatcher(12, ed));
        }

        ed.setText(content);
        ed.setSelection(ed.length());
        findViewById(R.id.ll_btn).setVisibility(View.GONE);
        initView();
        initNextView();
    }


    private TextView tvPre;
    private TextView tvNext;

    private void initNextView() {


        tvNext = (TextView) findViewById(R.id.tv_next);
        tvPre = (TextView) findViewById(R.id.tv_pre);
        if ("4".equals(type)) {//等级
            tvNext.setText("选好了");
        }else {
            tvNext.setText("下一步");
        }
        tvPre.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                preView();
            }
        });
        tvNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                ed.setText("");
                nextView();
            }
        });
    }


    private void preView() {
        finish();
    }

    private void nextView() {
        String s = ed.getText().toString();
        if ("4".equals(type)) {//等级
            if (s != null && s.length() >0 && s.length() < 2){
                toast("请输入2-5个字");
                return;
            }
            intoProduct();
        } else if ("2".equals(type)) {//品牌

            intoLevel();
        } else if ("3".equals(type)) {//产地
            intoBrand();
        } else if ("5".equals(type)) {//品名

            species = s;
            if (species != null && !"".equals(species)) {
                intoVariety();
            }else {
                toast("请添加品名");
            }
        }


    }

    private void intoProduct() {
        level = ed.getText().toString();
        ProductAddEntity productAddEntity = DataManager.getInstance().getProductAddEntity();
        productAddEntity.setLevel(level);
        Intent intent = new Intent(this, ProductAddActivity.class);
        String productType = productAddEntity.getType();
        //现售1
        intent.putExtra(Constant.TYPE, productType);

        String id = String.valueOf(productAddEntity.getId());
        if (id != null && !"".equals(id)){

            intent.putExtra("is_first", true);
        }else {
            intent.putExtra("is_first", false);
        }
        intent.putExtra("tagPackage", getIntent().getStringExtra("tagPackage"));
        startActivity(intent);
    }

    private void intoVariety() {
        species = ed.getText().toString();
        ProductAddEntity productAddEntity = DataManager.getInstance().getProductAddEntity();
        productAddEntity.setSpecies(species);
        Intent intent = new Intent(this, ProductAddCategoryVarietiesActivity.class);
//        intent.putExtra("categoryId", productAddEntity.getCategoryId());
        intent.putExtra("nameId", productAddEntity.getNameId());
        intent.putExtra("tagPackage", getIntent().getStringExtra("tagPackage"));

        startActivity(intent);
    }

    private void intoLevel() {
        brand = ed.getText().toString();
        ProductAddEntity productAddEntity = DataManager.getInstance().getProductAddEntity();

        productAddEntity.setBrand(brand);
        Log.e("productAddEntity","productAddEntity-brand:"+productAddEntity);
//        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//        imm.hideSoftInputFromWindow(ed.getWindowToken(), 0); //强制隐藏键盘
        Intent intent = new Intent(this, ProductAddOtherActivity.class);
        intent.putExtra("page_type", "4");
        intent.putExtra("varietyName", productAddEntity.getVariety());
        intent.putExtra("nameId", productAddEntity.getNameId());
        intent.putExtra("tagPackage", getIntent().getStringExtra("tagPackage"));
        startActivity(intent);
    }

//    private void intoArea() {
//        ProductAddEntity productAddEntity = DataManager.getInstance().getProductAddEntity();
//
//
//        Intent intent = new Intent(this, ProductAddOtherActivity.class);
//        intent.putExtra("page_type", "3");
//        intent.putExtra("varietyName", productAddEntity.getVariety());
//        intent.putExtra("nameId", productAddEntity.getNameId());
//
//
//        startActivity(intent);
//    }

    private void intoBrand() {
        area = ed.getText().toString();
        ProductAddEntity productAddEntity = DataManager.getInstance().getProductAddEntity();

        productAddEntity.setOrigin(area);

//        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//        imm.hideSoftInputFromWindow(ed.getWindowToken(), 0); //强制隐藏键盘
        Intent intent = new Intent(this, ProductAddOtherActivity.class);
        intent.putExtra("page_type", "2");
        intent.putExtra("varietyName", productAddEntity.getVariety());
        intent.putExtra("nameId", productAddEntity.getNameId());
        intent.putExtra("tagPackage", getIntent().getStringExtra("tagPackage"));
        startActivity(intent);
    }

    protected void initAddView() {
//        toolbarTitle.setText("品种");
        ivBack.setVisibility(View.VISIBLE);
        tvBack.setVisibility(View.VISIBLE);

        View view = findViewById(R.id.ly_add);
        ed = (EditText) view.findViewById(R.id.et_add_content);
        tvAdd = (TextView) view.findViewById(R.id.tv_add_search);

        tvAdd.setText("清空");
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(ed.getWindowToken(), 0); //强制隐藏键盘
                finish();
            }
        });

        tvAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                add();
                ed.setText("");
            }
        });



    }


    public void add() {
        String s = ed.getText().toString();
        if (s == null || "".equals(s)) {
            if ("4".equals(type)) {//等级
                toast("请添加等级");
            } else if ("2".equals(type)) {//品牌
                toast("请添加品牌");
            } else if ("3".equals(type)) {//产地
                toast("请添加产地");
            }else if ("5".equals(type)) {//品名
                toast("请添加品名");
            }
            return;
        }


            if ("4".equals(type)) {//等级
               level = s;
            } else if ("2".equals(type)) {//品牌
                brand = s;
            } else if ("3".equals(type)) {//产地
                area = s;
            }else if ("5".equals(type)) {//品名
                species = s;
            }

        nextView();
//        Intent intent = new Intent();
//
//        intent.putExtra("result", s);
//
//        setResult(RESULT_OK, intent);
//        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//        imm.hideSoftInputFromWindow(ed.getWindowToken(), 0); //强制隐藏键盘
//        finish();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {

        outState.putString("area", area);
        outState.putString("brand", brand);
        outState.putString("level", level);
        outState.putString("page_type", type);
        outState.putString("productId", productId);
        outState.putString("varietyName", varietyName);
        outState.putString("nameId", nameId);
        outState.putString("content", content);
        outState.putString("species", species);
        outState.putString("tagPackage", getIntent().getStringExtra("tagPackage"));

        ProductAddEntity productAddEntity = DataManager.getInstance().getProductAddEntity();
        if(productAddEntity != null) {
            outState.putString("dataProduct", new Gson().toJson(productAddEntity));
        }
        super.onSaveInstanceState(outState);
    }


    private void initView() {
        tagW = LocalDisplay.SCREEN_WIDTH_PIXELS - LocalDisplay.dp2px(46);
        tagW /= 3;

        tagFlowLayout = (TagFlowLayout) findViewById(R.id.t_tag);

        tagFlowLayout.setMaxSelectCount(1);

        tagAdapter = new TagAdapter<String>(list) {
            @Override
            public View getView(FlowLayout parent, int position, String s) {
                TextView tv = (TextView) LayoutInflater.from(ProductAddOtherActivity.this).inflate(R.layout.product_add_tag,
                        parent, false);
                ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) tv.getLayoutParams();
                lp.width = tagW;
//                if (position %3 == 0){
//                    lp.leftMargin = LocalDisplay.dp2px(15);
//                }else {
//                    lp.leftMargin = LocalDisplay.dp2px(8);
//                }
//                lp.rightMargin = 0;
//                lp.topMargin = LocalDisplay.dp2px(4);
//                lp.bottomMargin = LocalDisplay.dp2px(4);
                tv.setText(s);
                return tv;
            }
        };
        tagFlowLayout.setAdapter(tagAdapter);

        tagFlowLayout.setOnSelectListener(new TagFlowLayout.OnSelectListener() {
            @Override
            public void onSelected(Set<Integer> selectPosSet) {

                if (selectPosSet != null && selectPosSet.size() > 0) {
                    for (Integer i : selectPosSet) {
                        if(i < list.size()) {
                            varietyName = list.get(i);
                            ed.setText(varietyName);
                            ed.setSelection(ed.length());
                        }
                    }

                    tagAdapter.setSelectedList(new HashSet<Integer>());
                }else {
                    ed.setText("");
                }
            }
        });
//        tagFlowLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
//            @Override
//            public boolean onTagClick(View view, int position, FlowLayout parent) {
//                if (position < list.size()) {
////                    tagAdapter.setSelectedList(position);
//                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//                    imm.hideSoftInputFromWindow(ed.getWindowToken(), 0); //强制隐藏键盘
//                    String result = list.get(position);
//
//                    if ("4".equals(type)) {//等级
//                        level = result;
//                    } else if ("2".equals(type)) {//品牌
//                        brand = result;
//                    } else if ("3".equals(type)) {//产地
//                        area = result;
//                    }else if ("5".equals(type)) {//品名
//                        species = result;
//                    }
//
//
//                    nextView();
////                    Intent intent = new Intent();
////                    intent.putExtra("result", result);
////                    setResult(RESULT_OK, intent);
////                    finish();
//                }
//                return true;
//            }
//        });


//        test();

    }


    public void updateTag(List<String> list) {
        this.list.clear();
        if (list != null) {
            this.list.addAll(list);
        }
        tagAdapter.notifyDataChanged();
//        for (int i = 0; i < this.list.size(); i++) {
//            String s = this.list.get(i);
//            if (s != null && !"".equals(s)&& s.equals(content)){
//                tagAdapter.setSelectedList(i);
//            }
//        }
    }

    @Override
    protected void onToolbarBack() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(ed.getWindowToken(), 0); //强制隐藏键盘
        super.onToolbarBack();
    }

    @Override
    public void onBackPressed() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(ed.getWindowToken(), 0); //强制隐藏键盘
        super.onBackPressed();
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.tv_btn:

                break;
        }
    }

    public void request(String nameId, String variety, String field) {

        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_category_getMore);
        RequestEntityMapSupply.putParameter("nameId", nameId);
        if (variety == null) {
            variety = "";
        }
        RequestEntityMapSupply.putParameter("variety", variety);
        RequestEntityMapSupply.putParameter("field", field);

        request(RequestEntityMapSupply, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_category_getMore, onCategoryTreeRequestListener);

    }


    private OnRequestListener<List<String>> onCategoryTreeRequestListener = new OnRequestListener<List<String>>() {
        @Override
        public List<String> jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, new TypeToken<List<String>>() {
            }.getType());
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<List<String>> response, Object tag) {


            List<String> responseElement = response.getResponseElement();

            if (responseElement != null && responseElement.size() > 0) {

                updateTag(responseElement);

            }
        }
    };

}
